//
// Created by antler on 2018/12/5.
//

#include "RuntimeUtils.h"

#include <string>
#include <sstream>

#include "LuaJavaHelper.h"

#include "JNIDef.h"

namespace RuntimeUtils {
    bool launchApp(const char *packageName, const char *componentName) {
        JNIEnv *env = LuaJavaHelper::getInstance()->getEnv();
        if (!env) {
            return false;
        }

        jboolean result = JNI_FALSE;

        ScopedLocalRef<jstring> jPackageName(env, env->NewStringUTF(packageName));
        ScopedLocalRef<jstring> jComponentName(env, env->NewStringUTF(componentName));
        if (jPackageName) {
            result = LuaJavaHelper::callStaticBooleanMethod(env, CLASS_NAME_RUNTIMEUTILS,
                                                            METHOD_NAME_RUNTIMEUTILS_LAUNCHAPP,
                                                            METHOD_SIG_RUNTIMEUTILS_LAUNCHAPP,
                                                            (jstring) jPackageName,
                                                            (jstring) jComponentName);
        }

        return result ? true : false;
    }

    void killApp(const char *packageName) {
        JNIEnv *env = LuaJavaHelper::getInstance()->getEnv();
        if (!env) {
            return;
        }

        std::ostringstream ss;
        ss << "am force-stop ";
        ss << "\"";
        ss << packageName;
        ss << "\"";

        LuaJavaHelper::runShellCommand(env, ss.str().c_str(), true, nullptr, 0);
    }

    void inputText(const char *inputText) {
        JNIEnv *env = LuaJavaHelper::getInstance()->getEnv();
        if (!env) {
            return;
        }

        ScopedLocalRef<jstring> jInputText(env, env->NewStringUTF(inputText));
        if (jInputText) {
            LuaJavaHelper::callStaticVoidMethod(env, CLASS_NAME_RUNTIMEUTILS,
                                                METHOD_NAME_RUNTIMEUTILS_INPUTTEXT,
                                                METHOD_SIG_RUNTIMEUTILS_INPUTTEXT,
                                                (jstring) jInputText);
        }
    }
};